package cn.zy.register.service.impl;

import cn.hutool.core.lang.generator.ObjectIdGenerator;
import cn.lj.common.redis.constant.RedisConstant;
import cn.zy.common.alisms.dto.AUTHCode;
import cn.zy.common.encryption.AuthRandomUtils;
import cn.zy.common.redis.JacksonUtil;
import cn.zy.common.redis.RedisServie;
import cn.zy.common.util.BeanCopierUtil;
import cn.zy.common.utils.RestResult;
import cn.zy.common.utils.RestResultEmum;
import cn.zy.init.DataConstant;
import cn.zy.register.mapper.bo.SmallMiUserBO;
import cn.zy.register.mapper.domain.SmallMiUserDO;
import cn.zy.register.mapper.mapper.SmallMiUserMapper;
import cn.zy.register.mapper.pojo.SmallMiUser;
import cn.zy.register.mapper.qo.SmallMiUserQO;
import cn.zy.register.service.SmallMiUserService;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
@Service("smallMiUserServiceImpl")
public class SmallMiUserServiceImpl implements SmallMiUserService {


    @Autowired
    private SmallMiUserMapper smallMiUserMapper;

    @Autowired
    private RedisServie redisServie;

    @Autowired
    private Client client;


    /**
     * 查询全部user表
     * @return
     */
    @Override
    public List<SmallMiUser> getAll() {
        return smallMiUserMapper.getAll();
    }

    /**
     * 输入手机号获取验证码
     * @param code
     * @return
     */
    @Override
    public RestResult<String> getcode(String code) {

        AUTHCode authCode = new AUTHCode();
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(code);
        sendSmsRequest.setSignName("BaseAdmin管理");
        sendSmsRequest.setTemplateCode("SMS_218290669");
        //先拿一下reids中的key，看看有没有，如果有直接使用，没有就创建
        AUTHCode obj = redisServie.getObj(DataConstant.USER_CODE + code, AUTHCode.class);
        //如果reids有验证码了
        if (obj != null) {
            //给验证码失效时间再重置为5分钟
            redisServie.expire(DataConstant.USER_CODE + code, 60 * 5L);
            //把拿到的的对象转成json传入并发送短信
            String s = JacksonUtil.toJsonStr(obj);
            sendSmsRequest.setTemplateParam(s);
            try {
                client.sendSms(sendSmsRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new RestResult<>(RestResultEmum.REGISTER_SUCCESSFULLY.code, RestResultEmum.REGISTER_SUCCESSFULLY.msg);
        }

        //生成验证码
        String authCodes = AuthRandomUtils.getAuthCode(6);
        authCode.setCode(authCodes);
        String s = JacksonUtil.toJsonStr(authCode);
        //与模板中的json字符串要对应
        sendSmsRequest.setTemplateParam(s);
        //将验证码工具类生成的验证码存到redis
        redisServie.setObj(DataConstant.USER_CODE + code, authCode, 60 * 5L);
        try {
            client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new RestResult<>(RestResultEmum.REGISTER_SUCCESSFULLY.code, RestResultEmum.REGISTER_SUCCESSFULLY.msg, code);

    }


    /**
     * 注册验证
     * @param mi_phone
     * @param code
     * @param agreement
     * @return
     */
    @Override
    public RestResult<SmallMiUserDO> register(SmallMiUserBO mi_phone, String code, String agreement) {
        SmallMiUserQO smallMiUserQO = BeanCopierUtil.copyObj(mi_phone, SmallMiUserQO.class);
        SmallMiUserDO smallMiUserDO = BeanCopierUtil.copyObj(smallMiUserQO, SmallMiUserDO.class);
        //判断手机号是否为11位
        int length = mi_phone.getMi_phone().length();
        if (length != 11) {
            return new RestResult<SmallMiUserDO>(RestResultEmum.ERROR_LENGTH.code, RestResultEmum.ERROR_LENGTH.msg, smallMiUserDO);
        }
        if (!agreement.equals("1")) {//没有同意用户协议
            return new RestResult<SmallMiUserDO>(RestResultEmum.CONSENT_USER_TERMS.code, RestResultEmum.CONSENT_USER_TERMS.msg, smallMiUserDO);
        }
        AUTHCode code1 = redisServie.getObj(DataConstant.USER_CODE + mi_phone.getMi_phone(), AUTHCode.class);
        if (code1 == null) {//判断发送的验证码是不是这个手机号
            return new RestResult<>(RestResultEmum.REGISTER_AUTH_EXTIST.code, RestResultEmum.REGISTER_AUTH_EXTIST.msg, smallMiUserDO);
        }

        if (!code.equals(code1.getCode())) {//验证码错误
            return new RestResult<>(RestResultEmum.REGISTER_AUTH_EXTIST.code, RestResultEmum.REGISTER_AUTH_EXTIST.msg, smallMiUserDO);
        }
        //判断手机注册了没有
        SmallMiUserDO hash = redisServie.getHash(DataConstant.USER_DATA, mi_phone.getMi_phone(), SmallMiUserDO.class);
        if (hash != null) {//已经注册了
            return new RestResult<>(RestResultEmum.REGISTER_EXTIST.code, RestResultEmum.REGISTER_EXTIST.msg, hash);
        }
        return new RestResult<>(RestResultEmum.ENTER_YOUR_PIN.code, RestResultEmum.ENTER_YOUR_PIN.msg, smallMiUserDO);
    }


    /**
     * 已注册登录  判断密码是否正确
     * @param mi_phone
     * @param mi_pass_word
     * @return
     */
    @Override
    public RestResult<SmallMiUserDO> verifyLogin(String mi_phone, SmallMiUserBO mi_pass_word) {
        SmallMiUserQO smallMiUserQO = BeanCopierUtil.copyObj(mi_pass_word, SmallMiUserQO.class);
        //从redis中获取用户数据
        SmallMiUserDO hash = redisServie.getHash(DataConstant.USER_DATA, mi_phone, SmallMiUserDO.class);

        if (hash == null) {
            smallMiUserQO.setMi_phone(mi_phone);
            SmallMiUser smallMiUser = smallMiUserMapper.verifyLogin(smallMiUserQO);
            if (smallMiUser == null) {//数据库数据中没有的话
                return new RestResult<>(RestResultEmum.PASSWORD_ERROR.code, RestResultEmum.PASSWORD_ERROR.msg);
            }
            //数据库查询正确登录成功
            SmallMiUserDO smallMiUserDO = BeanCopierUtil.copyObj(smallMiUser, SmallMiUserDO.class);
            return new RestResult<>(RestResultEmum.REGISTER_SUCCEED.code, RestResultEmum.REGISTER_SUCCEED.msg, smallMiUserDO);
        }

        if (hash.getMi_pass_word().equals(mi_pass_word.getMi_pass_word())) {//redis中数据正确
            return new RestResult<>(RestResultEmum.REGISTER_SUCCEED.code, RestResultEmum.REGISTER_SUCCEED.msg, hash);
        }

        smallMiUserQO.setMi_phone(mi_phone);
        SmallMiUser smallMiUser = smallMiUserMapper.verifyLogin(smallMiUserQO);
        if (smallMiUser == null) {//数据库数据中没有的话
            return new RestResult<>(RestResultEmum.PASSWORD_ERROR.code, RestResultEmum.PASSWORD_ERROR.msg);
        }
        //数据库查询正确登录成功
        SmallMiUserDO smallMiUserDO = BeanCopierUtil.copyObj(smallMiUser, SmallMiUserDO.class);
        return new RestResult<>(RestResultEmum.REGISTER_SUCCEED.code, RestResultEmum.REGISTER_SUCCEED.msg, smallMiUserDO);

    }


    /**
     * 生成小米账号
     * @return
     */
    @Override
    public RestResult<SmallMiUserDO> setMiAccount(SmallMiUserBO smallMiUserBO) {

        int length = smallMiUserBO.getMi_phone().length();
        if (length != 11) {
            return new RestResult<>(RestResultEmum.ERROR_LENGTH.code, RestResultEmum.ERROR_LENGTH.msg);
        }
        //设置小米账号(时间戳)
        long l = System.currentTimeMillis();
        String mi_id = String.valueOf(l);
        smallMiUserBO.setMi_id(mi_id);//小米ID
        smallMiUserBO.setMi_phone(smallMiUserBO.getMi_phone());//手机号

        //判断俩次输入的密码是否相等
        if (!smallMiUserBO.getMi_pass_word().equals(smallMiUserBO.getTwicePwd())) {
            //不相等
            return new RestResult<>(RestResultEmum.PASSWORDTWO_ERROR.code, RestResultEmum.PASSWORDTWO_ERROR.msg);
        }
        smallMiUserBO.setMi_pass_word(smallMiUserBO.getMi_pass_word());//小米密码
        smallMiUserBO.setMi_status("3"); //1 封停 , 2 冻结 , 3 正常
        smallMiUserBO.setMi_encrypted("no");// yes/no
        smallMiUserBO.setMi_permission("admin");//权限
        smallMiUserBO.setMi_icon_url("C:\\Users\\zhangyu\\Desktop\\图片.jpeg");//图片url
        smallMiUserBO.setCreation_date(new Date());//创建时间
        smallMiUserBO.setCreated_by("张宇");//创建者
        smallMiUserBO.setVersion("1.0"); // 版本号
        smallMiUserBO.setModifieBy("张宇");//更新者

        SmallMiUserQO smallMiUserQO = BeanCopierUtil.copyObj(smallMiUserBO, SmallMiUserQO.class);
        SmallMiUserDO smallMiUserDO = BeanCopierUtil.copyObj(smallMiUserQO, SmallMiUserDO.class);
        //从redis中获取用户数据(是否已经添加)
        SmallMiUserDO hash = redisServie.getHash(DataConstant.USER_DATA, smallMiUserBO.getMi_phone(), SmallMiUserDO.class);
        if (hash == null) {
            //相等 则判断有没有选择协议(不管有没有选择都添加用户) 给数据库和redis中添加
            if (smallMiUserBO.getAgreement().equals("1")) {// 选择了协议 添加用户信息(数据库)
                Integer integer = smallMiUserMapper.setMiAccount(smallMiUserQO);
                if (integer == 1) {//新增成功
                    redisServie.putHash(DataConstant.USER_DATA, smallMiUserBO.getMi_phone(), smallMiUserQO);
                    return new RestResult<>(RestResultEmum.SUCCESS.code, RestResultEmum.SUCCESS.msg, smallMiUserDO);
                }
            }
            //没选择协议(也添加用户信息    )
            Integer integer = smallMiUserMapper.setMiAccount(smallMiUserQO);
            if (integer == 1) {//新增成功
                redisServie.putHash(DataConstant.USER_DATA, smallMiUserBO.getMi_phone(), smallMiUserQO);
                return new RestResult<>(RestResultEmum.TWICE_USER_TERMS.code, RestResultEmum.TWICE_USER_TERMS.msg);
            }
        }
        return new RestResult<>(RestResultEmum.REGISTER_EXTIST.code, RestResultEmum.REGISTER_EXTIST.msg);

    }



}
